﻿using FirstFloor.ModernUI.Windows.Controls;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;

namespace Atlanchim.Crm.Mui.Helpers
{
    public static class PersistenceErrorHelper
    {
        public static string GetEntityValidationErrorMessages(DbEntityValidationException entityValidationException)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var eve in entityValidationException.EntityValidationErrors)
            {
                sb.AppendFormat("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                sb.AppendLine();
                foreach (var ve in eve.ValidationErrors)
                {
                    sb.AppendFormat("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                    sb.AppendLine();
                }
            }

            return sb.ToString();
        }

        public static void ShowErrors(DbEntityValidationException errors)
        {
            string message = PersistenceErrorHelper.GetEntityValidationErrorMessages(errors);
            ModernDialog.ShowMessage(message, "Erreur", System.Windows.MessageBoxButton.OK);
        }
    }
}
